<?php
/********************************************************
 *
 * 此文件的作用:
 *		包括工资的所有操�?
 *
 * @copyright Copyright (c) 2008-2009
 * @author 刘昌�? lcg635@126.com
 *
 ********************************************************/
defined('APP_DIR') or header("HTTP/1.0 404 Not Found");

FLEA::loadClass('Common_Model');

class Model_Wage extends Common_Model {

	function __construct() {
		parent::__construct();
		$this->_tb = FLEA::getSingleton('Table_Wage');
	}
	
	function import($wagesData, $month, $type = 0) {
		$year = date('Y');
		$lastday = date('Y-m-d', mktime(0, 0, 0, date('m')+1, 0, $year));
		$created = $year . '-' . $month . '-02';
		$cond = 'created >= \'' . $year . '-' . $month . '01\' and created <= \'' . $lastday . '\'';
		$result = array();
		if (0 == $type)
			$this->_tb->removeByConditions($cond);
		
		$this->_tb->dbo->startTrans();
		__TRY();
		foreach ($wagesData as $wage) {
			$wage['created'] = $created;
			$this->_tb->create($wage) or $result['failure'][] = $wage['num'];
		}
		$ex = __CATCH();
		$this->_tb->dbo->completeTrans();
		$result['resultNum'] = $this->_tb->findCount($cond);
		return $result;
	}
	
	function search($searchDatas) {
		setcookie('searchDatasInForm', serialize($searchDatas), time()+7200, '/');
		$validateColumns = array('num', 'station', 'bankCardNum', 'startDate', 'finishDate', 'sort', 'by');
		foreach ($searchDatas as $k => $searchData) {
			if ( !in_array($k, $validateColumns) || empty($searchData) ) {
				unset($searchDatas[$k]);
				continue;
			}
			if ( 'startDate' == $k ) { 
				$searchDatas[] = 'created >= \'' . $searchData . '\'';
				unset($searchDatas[$k]);
			}
			if ( 'finishDate' == $k ) { 
				$searchDatas[] = 'created <= \'' . $searchData . '\'';
				unset($searchDatas[$k]);
			}
		}
		setcookie('searchWages', serialize($searchDatas), time()+7200, '/');
	}
	
	function getSearchResult($page = 0) {
		$searchDatas = unserialize($_COOKIE['searchWages']);
		if ( empty($searchDatas) ) return null;	
		$sortBy = $searchDatas['sort'] . ' ' . $searchDatas['by'];
		unset($searchDatas['sort']);unset($searchDatas['by']);
		
		FLEA::loadHelper('pager');
		$pager = new FLEA_Helper_Pager($this->_tb, $page, '10', $searchDatas, $sortBy);
		$result = array(
			'lists' => $pager->findAll(),
			'pagerData' => $pager->getPagerData()
		);
		return $result;
	}
	
	function getWagesByNum($num) {
		return $this->_tb->findAll('num = \'' . $num . '\'', 'created desc');
	}
	
	function getSearchingForm() {
		$searchDatas = unserialize($_COOKIE['searchDatasInForm']);
		return $this->getForm($searchDatas);
	}
	
	function getForm($data = null) {
		return $this->_tb->form($data);
	}
}